package com.hmall.gateway.filters;

import com.hmall.common.exception.UnauthorizedException;
import com.hmall.common.utils.CollUtils;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.config.JwtProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@RequiredArgsConstructor
@EnableConfigurationProperties(AuthProperties.class)
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final JwtTool jwtTool;


    private final AuthProperties authProperties;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("登陆拦截器");
        //1. 获取请求头
        ServerHttpRequest request = exchange.getRequest();
        System.out.println("拦截判断的URL：" + request.getPath().toString());
        //2. 判断请求头是不是拦截范围之外的
        if(isExclude(request.getPath().toString())){
            //无需拦截，直接放行
            return chain.filter(exchange);
        }
        //3. 获取请求头中的token
        String token = null;
        List<String> headers = request.getHeaders().get("authorization");
        if (!CollUtils.isEmpty(headers)) {
            token = headers.get(0);
        }
        //4. 检验并解析token
        Long userId = null;
        try {
            userId = jwtTool.parseToken(token);
        } catch (UnauthorizedException e) {
            // 如果无效，拦截
            ServerHttpResponse response = exchange.getResponse();
            response.setRawStatusCode(401);
            return response.setComplete();
        }
        //5. 有效就传递用户信息
        String userInfo = userId.toString();
        ServerWebExchange nextExchange = exchange.mutate()
                .request(builder -> builder.header("user-info", userInfo))
                        .build();
        System.out.println("userId" + userId);
        //6. 放行
        return chain.filter(nextExchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    private boolean isExclude(String antPath){
        List<String> list = authProperties.getExcludePaths();
        for (String url : list){
            if(antPathMatcher.match(url, antPath)){
                return true;
            }
        }
        return false;
    }
}
